package org.dna.wickwtui.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.dna.MetroApplication;
import org.dna.UserRoles;
import org.dna.metronomo.persistence.Activity;
import org.dna.uimodel.LoadableActivityModel;
import org.dna.uimodel.MenuItem;
import org.dna.uimodel.SelectableActivity;
import org.dna.wickwtui.users.IContextMenuProvider;

public class ActivityListPanel extends Panel implements IContextMenuProvider {

	private final static Logger LOG = Logger.getLogger(ActivityListPanel.class);
	private final static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

	@UserRoles( { "admin" })
	private class DeleteLink extends SubmitLink {

		private static final long serialVersionUID = -5681232486590259371L;

		public DeleteLink(String id) {
			super(id, m_form);
		}

		@Override
		public void onSubmit() {
			// TODO call the backend and update the view, AJAX??
			LOG.info("Removing selected activities");
			int[] idstoDel = collectDeleted();
			//TODO refactor in a method inside the DAO
			for (int i : idstoDel) {
				MetroApplication.get().getActivityDAO().deleteActivityByID(i);
			}
			m_activities.detach(); //force the detach to update the list at next usage
			LOG.debug("Update the activities table with " + m_activities.getObject());
		}
		
		private int[] collectDeleted() {
			List<Integer> l = new ArrayList<Integer>();
			for (Activity activity : m_activities.getObject()) {
				SelectableActivity suser = (SelectableActivity) activity;
				if (suser.isSelected()) {
					l.add(activity.getId());
                    LOG.debug("Adding selected activity " + activity);
				}
			}

			// Copy the list of Integer to int[]
			int[] ret = new int[l.size()];
			for (int i = 0; i < ret.length; i++) {
				ret[i] = l.get(i);
			}
            LOG.debug("Selected activities IDs " + Arrays.toString(ret));
			return ret;
		}
	}

	@UserRoles( { "admin", "user" })
	private class DetailsActivityLink extends Link<Activity> {

		private static final long serialVersionUID = -5294465353231762744L;

		public DetailsActivityLink(String id, IModel<Activity> actModel) {
			super(id, actModel);
		}

		@Override
		public void onClick() {
			((ManageActivityPage) getPage()).switchToPanel(
					ActivityDetailsPanel.class, (Activity)getModelObject());
		}
	}

	private static final long serialVersionUID = 1L;

	private static final int ITEM_PER_PAGE = 5;

	Form<List<? extends Activity>> m_form;
	PageableListView<Activity> m_activitiesView;
	IModel<List<SelectableActivity>> m_activities;

	public ActivityListPanel(String id, IModel<List<SelectableActivity>> sacts) {
		super(id);
		m_activities = sacts;
		initComponents(sacts);
	}

	private void initComponents(IModel<List<SelectableActivity>> acts) {
		m_form = new Form<List<? extends Activity>>("form") {
			@Override
			public void onSubmit() {
				LOG.debug("Actually selected activities for deletion " + m_activities);
			}
		};

		m_activitiesView = new PageableListView<Activity>("activities", acts,
				ITEM_PER_PAGE) {

			@Override
			protected void populateItem(ListItem<Activity> item) {
				Activity activity = item.getModelObject();
				IModel<Activity> activityModel = new LoadableActivityModel(activity);
				item.setModel(new CompoundPropertyModel<Activity>(activityModel));

				DetailsActivityLink link = new DetailsActivityLink("link",
						activityModel);
				link.add(new Label("name"));
				item.add(link);
				item.add(new MultiLineLabel("description"));
				item.add(new Label("effort", activity.getEffort().toString()));
				item.add(new Label("estimated", activity.getEstimatedEffort().toString()));

				int numJobs = activity.getJobs().size();
				Label lblNumJobs = new Label("numJobs", Integer
						.toString(numJobs));
				lblNumJobs.setVisible(numJobs != 0); // with this we hide also
														// the link
				item.add(lblNumJobs);
				String formattedDate = sdf.format(activity.getEstimatedStart());
				item.add(new Label("startDate", formattedDate));
				item.add(new CheckBox("selected"));
			}
		};
		m_form.add(m_activitiesView);
		add(m_form);
		add(new PagingNavigator("navigator", m_activitiesView));
	}

	public List<MenuItem> prepare() {
		MenuItem deleteSelectedUsersItem = new MenuItem("Delete",
				ManageActivityPage.class) {

			@Override
			public Component createMenu() {
				DeleteLink link = new DeleteLink("link");
				link.add(new SimpleAttributeModifier("onclick",
						"return confirm(’remove definition?’);"));
				link.add(new Label("caption", getCaption()));
				return link;
			}
		};
		return Arrays.asList(deleteSelectedUsersItem);
	}
}
